package org.example.interceptor;
import org.example.entity.User;
import org.example.exception.BizCodeEnum;
import org.example.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.example.utils.R;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<User> threadLocal  = new ThreadLocal<>();
    @Autowired
    private RedisService redisService;

    public static HashMap<Integer, ArrayList<String>> hashMap;
    static {
        hashMap = new HashMap<>();
        ArrayList<String>  arrayList = new ArrayList<>();
        arrayList.add("/clan/findFamilyTree");
        arrayList.add("/family/showFamily");
        hashMap.put(1,arrayList);
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {

        String token = request.getHeader("token");
        User user = redisService.getUser(token);
        if(user==null) {
            response.setContentType("application/json;charset=utf-8");
            R r = R.error(1001,"先登录");
            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(r));
            pw.flush();
            pw.close();
            return false;
        } else if (user.isChild==1) {
            if(isLegal(request.getRequestURI())) return true;
            else {
                response.setContentType("application/json;charset=utf-8");
                R r = R.error(BizCodeEnum.PERMISSION_DENY.getCode(), BizCodeEnum.PERMISSION_DENY.getMsg());
                PrintWriter pw = response.getWriter();
                pw.write(JSON.toJSONString(r));
                pw.flush();
                pw.close();
                return false;
            }
        }
         else {
            threadLocal.set(user);
            return true;
        }
    }

    public boolean isLegal(String requestURI){
        for (String s :hashMap.get(1)
        ) {
            if(requestURI.matches(s))
                return true;
        }
        return false;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        String token = response.getHeader("token");
//        User user = threadLocal.get();
//        redisService.setUser(token,user);
//        //删除老的token和User信息
////        redisService.deleteToken(user.id);
//        //设置新的token
//        redisService.setToken(user.id, token);
//        //TODO 还未测试
//    }
}
